import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import commandes.Commande;
import commandes.CommandeAjoutClient;
import commandes.CommandeAjoutLocation;
import commandes.CommandeAuthentification;
import commandes.CommandeClients;
import commandes.CommandeLogCrit;
import commandes.CommandeMajClients;
import commandes.CommandeMajLocation;
import commandes.CommandeMajLogement;
import commandes.CommandeMajProprietaire;
import commandes.CommandePropLog;
import commandes.CommandeProprietaires;
import commandes.NullCommande;


public class Controleur extends HttpServlet {
	private Map<String,Commande> cdes;
	
	public void init(ServletConfig config) throws ServletException {
		cdes = new HashMap<String,Commande>();
			cdes.put("accueil", new NullCommande("accueil.jsp"));
			cdes.put("clients",new CommandeClients("clients.jsp"));
			cdes.put("proprietaires",new CommandeProprietaires("proprietaires.jsp"));
			cdes.put("logements",new CommandePropLog("logements.jsp"));
			cdes.put("logementsCrit",new CommandeLogCrit("logementsCrit.jsp"));
			cdes.put("authentification", new CommandeAuthentification("accueil.jsp"));
			cdes.put("MAJproprietaires", new CommandeMajProprietaire("MAJproprietaires.jsp"));
			cdes.put("MAJclients", new CommandeMajClients("MAJclients.jsp"));
			cdes.put("MAJlogements", new CommandeMajLogement("MAJlogements.jsp"));
			cdes.put("MAJlocations", new CommandeMajLocation("MAJlocations.jsp"));
			cdes.put("ajoutClient", new CommandeAjoutClient("ajoutClient.jsp"));
			cdes.put("ajoutLocation", new CommandeAjoutLocation("ajoutLocation.jsp"));


	}

	public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 

		String next=null;                               
		String cmd = req.getParameter("cmd");

		if (cmd==null) { cmd="accueil"; }
		else {
			if (! cdes.containsKey(cmd)) {
				RequestDispatcher rd1 = req.getRequestDispatcher("/erreurCommande.jsp");
				rd1.forward(req, res);
				return;
			}
		}

		Commande cde = cdes.get(cmd);                 
		try {
				next = cde.execute(req);
		} catch(Exception ex){}
		RequestDispatcher rd = req.getRequestDispatcher(next);
		rd.forward(req, res); 
	} 
}
